package com.jmlee.controller;

import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.Rider;
import com.jmlee.service.RiderService;
import com.jmlee.utils.CheckInCircle;
import com.jmlee.util.JSONUtil;
import com.jmlee.utils.Sample;
import com.jmlee.util.SecurityUtil;
import com.jmlee.vo.AddressByOrderVo;
import com.jmlee.vo.ChangePwdVo;
import com.jmlee.vo.GetRiderVo;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author： 郑锦涛
 * @data： 2021/3/8 16:25
 * @version：1.0
 * @描述： 骑手端控制层
 */
@RestController
@EnableScheduling
public class RiderController {

    @Autowired
    RiderService riderService;

    @Autowired
    WebSocketServerEndpoint webSocket;

    /**
     * 日志
     */
    private Logger LOGGER = LoggerFactory.getLogger(RiderController.class);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * 获取配置文件里的数据
     * 从配置properties文件中读取default.path.upload的值。
     * 从配置properties文件中读取default.password的值。
     */
    @Value("${default.path.upload}")
    private String uploadPath;
    @Value("${default.password}")
    private String password;


    /**
     * 骑手通过账号密码登录
     * @author： 郑锦涛
     * @param rider
     * @return
     */
    @RequestMapping("/riderLogin")
    public Rider riderLogin(@RequestBody Rider rider){
        //使用md5加密
        String password = SecurityUtil.getMD5(rider.getPassword());
        rider.setPassword(password);
        return riderService.riderLogin(rider);
    }

    /**
     * 使用微信openid登录
     * @param rider
     * @return
     */
    @RequestMapping("/loginByOpenid")
    public Rider loginByOpenid(@RequestBody Rider rider){
        return riderService.getChangeInfo(rider);
    }

    /**
     * 手机验证码登录
     *      --- 废弃预留功能  | 因申请不过废弃
     * @param mobile
     * @param vcode
     * @return
     */
    @RequestMapping("/riderLoginByTel")
    public Rider riderLoginByTel(@RequestParam("mobile") String  mobile,@RequestParam("vcode") String  vcode){
        return null;
    }



    /**
     *  获取订单
     * @author： 郑锦涛
     * @param getRiderVo    实体类
     * @return  满足条件的订单集合
     */
    @RequestMapping("/getOrder")
    public List<AddressByOrderVo> getOrder(@RequestBody GetRiderVo getRiderVo){
        if (getRiderVo.getOrderStatus() !=null){
            if (getRiderVo.getOrderStatus()==20 && getRiderVo.getUserName() == null && getRiderVo.getOpenid() == null){
                return  CheckInCircle.inCircleOrder(riderService.getOrderAddress(getRiderVo),WebSocketServerEndpoint.addressByRiderVo);
            }
        }
        return riderService.getOrderAddress(getRiderVo);
    }

    /**
     * 修改昵称
     * @author： 郑锦涛
     * @param rider 实体类
     * @return  改变昵称后的骑手数据
     */
    @RequestMapping("/changeNikeName")
    public Rider changeNikeName(@RequestBody Rider rider){
        return riderService.changeRiderInfo(rider);
    }

    /**
     * 修改密码
     * @param changePwdVo   实体类
     * @return  改变密码后的骑手数据
     */
    @RequestMapping("/changePwd")
    public Rider changePwd(@RequestBody ChangePwdVo changePwdVo){
        //使用md5加密
        String oldPwd = SecurityUtil.getMD5(changePwdVo.getOldPwd());
        String newPwd = SecurityUtil.getMD5(changePwdVo.getNewPwd());
        changePwdVo.setOldPwd(oldPwd);
        changePwdVo.setNewPwd(newPwd);
        Rider rider = new Rider();
        rider.setUsername(changePwdVo.getUsername());
        rider.setOpenid(changePwdVo.getOpenid());
        rider.setPassword(newPwd);
        return riderService.changePwd(changePwdVo,rider);
    }

    /**
     * 定时查看订单状态  该定时为5分钟查询一次
     * @throws IOException
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void sendOrderByWebSocket() throws IOException {
        //获取已付款状态的订单
        GetRiderVo getRiderVo = new GetRiderVo();
        getRiderVo.setOrderStatus(20);
        List<AddressByOrderVo> list = CheckInCircle.inCircleOrder(riderService.getOrderAddress(getRiderVo),WebSocketServerEndpoint.addressByRiderVo);
        if (list!=null){
            //将集合转json字符串
            String orderStr = JSONUtil.objectToJson(list);
            //调用服务器推送的方法
            webSocket.sendMessage(orderStr);
            //打印日志
            LOGGER.info("推送订单");
        }

    }


    /**
     * 接单
     * @param getRiderVo
     * @return
     */
    @RequestMapping("/takeOrder")
    public List<AddressByOrderVo> takeOrder(@RequestBody GetRiderVo getRiderVo){
        return riderService.takeOrder(getRiderVo);
    }

    /**
     * 取货
     * @param getRiderVo
     * @return
     */
    @RequestMapping("/pickUp")
    public List<AddressByOrderVo> pickUp(@RequestBody GetRiderVo getRiderVo){
        return riderService.pickUp(getRiderVo);
    }

    /**
     * 确认送达
     * @param getRiderVo
     * @return
     */
    @RequestMapping("/orderOver")
    public List<AddressByOrderVo> orderOver(@RequestBody GetRiderVo getRiderVo){
        return riderService.orderOver(getRiderVo);
    }

    /**
     * 获取坐标地点
     * @param getRiderVo
     * @return
     */
    @RequestMapping("/goEarth")
    public AddressByOrderVo goEarth(@RequestBody GetRiderVo getRiderVo){
        AddressByOrderVo address = riderService.goEarth(getRiderVo);
        return address;
    }

    /**
     * 上传身份证
     * @param request
     * @param username  id
     * @param file      身份证图片
     * @return  结果（成功/失败）
     * @throws Exception
     */
    @RequestMapping("/upLoadImg")
    public String upLoadImg(HttpServletRequest request,
                                          @RequestParam("username") String  username,
                                          @RequestParam("file") MultipartFile file) throws Exception{
        //得到身份证的所有信息
        JSONObject object = (JSONObject) Sample.sampleIdCard(file.getBytes()).get("words_result");
        //得到公民身份证号码
        JSONObject perJo = (JSONObject) object.get("公民身份号码");
        //获取识别的身份证号码
        String idNum = (String) perJo.get("words");
        if (!idNum.equals("")){

            // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
            String format = sdf.format(new Date());
            File folder = new File(uploadPath + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }

            // 对上传的文件重命名，避免文件重名
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString()
                    + oldName.substring(oldName.lastIndexOf("."), oldName.length());
            try {
                // 文件保存
                file.transferTo(new File(folder, newName));

                // 返回上传文件的访问路径,指定nginx的代理路径
                String filePath = "http://47.99.200.116/" + format + "/" + newName;

                Rider rider = new Rider();
                rider.setUsername(username);
                rider.setIdCard(idNum);
                rider.setIdCardImg(filePath);

                if (riderService.updateIdCard(rider)){
                    return JSONUtil.objectToJson(riderService.getChangeInfo(rider));
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "网络异常";
            }
        }
        return "身份证异常";
    }


    /**
     * 上传头像
     * @param request
     * @param username
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/upLoadHeardImg")
    public String upLoadHeardImg(HttpServletRequest request,
                                  @RequestParam("username") String  username,
                                  @RequestParam("file") MultipartFile file) throws Exception{

        // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;

            Rider rider = new Rider();
            rider.setUsername(username);
            rider.setHeaderImg(filePath);

            return JSONUtil.objectToJson(riderService.changeRiderInfo(rider));

        } catch (IOException e) {
            e.printStackTrace();
            return "网络异常";
        }

    }

    /**
     * 使用openid进行注册
     * @param rider
     * @return
     */
    @RequestMapping("/regByOpenid")
    public Rider regByOpenid(@RequestBody Rider rider){
        String pwd = SecurityUtil.getMD5(password);
        rider.setPassword(pwd);

        return riderService.regByOpenid(rider);
    }

    /**
     *  username 和 password 注册
     * @param rider
     * @return
     */
    @RequestMapping("/regByUsername")
    public String regByUsername(@RequestBody Rider rider){
        Rider checkUserName = riderService.getChangeInfo(rider);
        if (checkUserName != null){
            return "用户名已被注册";
        }else {
            //密码加密
            String password = SecurityUtil.getMD5(rider.getPassword());
            rider.setPassword(password);
            Integer reg = riderService.regByUsername(rider);
            if (reg>0){
                return "注册成功";
            }
            return "注册失败";
        }
    }

    /**
     * 查询全部订单
     * @param getRiderVo    传入用户名和状态
     * @return
     */
    @RequestMapping("/chooseOrder")
    public List<AddressByOrderVo> chooseOrder(@RequestBody GetRiderVo getRiderVo){
        return  riderService.chooseOrder(getRiderVo);
    }


}
